<template>
  <!-- 页面头部 -->
  <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; padding: 16px 0;">
    <div style="display: flex; align-items: center; gap: 12px;">
      <el-button v-if="formInline.parentId !== 0" @click="goBack" type="info" plain>
        ← 返回上级
      </el-button>
      <h2 style="margin: 0; font-size: 18px; font-weight: 500; color: #303133;">
        {{ formInline.parentId === 0 ? '科室列表' : '下级科室列表' }}
      </h2>
    </div>
    <el-button type="primary" style="background-color: #409EFF; border-color: #409EFF;" @click="openAddDialog">新增科室</el-button>
  </div>

<el-table :data="tableData" border style="width: 100%" ref="tableRef" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" />
    <el-table-column prop="id" type="index" label="序号"  />
    <el-table-column prop="name" label="科室名称"  />
    <el-table-column prop="introduction" label="级别"  />
    <el-table-column prop="status" label="状态"  >
        <template v-slot="a">
            <el-tag type="primary" v-if="a.row.status===true">上架</el-tag>
            <el-tag type="danger" v-if="a.row.status===false">下架</el-tag>
        </template>
    </el-table-column>
    <el-table-column prop="createTime" label="添加时间"  >
        <template v-slot="a">
                <span>
                {{ moment(a.row.createTime || a.row.createdAt || a.row.uploadTime || a.row.startTime).format("YYYY-MM-DD HH:mm:ss") }}
                </span>
        </template>
    </el-table-column>
    <el-table-column  label="操作" width="450">
        <template v-slot="a">
            <el-button @click="viewSubDepartments(a.row)">查看下级</el-button>
            <el-button @click="openEditDialog(a.row)">编辑</el-button>
            <el-button type="danger" @click="handleDelete(a.row)">删除</el-button>
        </template>
    </el-table-column>
  </el-table>

  <!-- 新增科室对话框 -->
  <el-dialog v-model="addDialogVisible" title="新增科室" width="500px" :before-close="handleCloseDialog">
    <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
      <el-form-item label="科室名称" prop="name">
        <el-input v-model="addForm.name" placeholder="请输入科室名称" />
      </el-form-item>
      <el-form-item label="上级分类" prop="parentId">
        <el-select v-model="addForm.parentId" placeholder="请选择上级分类" style="width: 100%">
          <el-option label="无上级分类（顶级分类）" :value="0" />
          <el-option 
            v-for="dept in parentDepartmentList" 
            :key="dept.id" 
            :label="dept.name" 
            :value="dept.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="科室介绍" prop="introduction">
        <el-input v-model="addForm.introduction" placeholder="请输入科室介绍" />
      </el-form-item>
      <el-form-item label="医院ID" prop="hospitalId">
        <el-input v-model.number="addForm.hospitalId" placeholder="请输入医院ID" type="number" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-switch v-model="addForm.status" active-text="启用" inactive-text="禁用" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button type="primary" @click="handleSubmitAdd">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 编辑科室对话框 -->
  <el-dialog v-model="editDialogVisible" title="编辑科室" width="500px" :before-close="handleCloseEditDialog">
    <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
      <el-form-item label="科室名称" prop="name">
        <el-input v-model="editForm.name" placeholder="请输入科室名称" />
      </el-form-item>
      <el-form-item label="上级分类" prop="parentId">
        <el-select v-model="editForm.parentId" placeholder="请选择上级分类" style="width: 100%">
          <el-option label="无上级分类（顶级分类）" :value="0" />
          <el-option 
            v-for="dept in parentDepartmentList" 
            :key="dept.id" 
            :label="dept.name" 
            :value="dept.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="科室介绍" prop="introduction">
        <el-input v-model="editForm.introduction" placeholder="请输入科室介绍" />
      </el-form-item>
      <el-form-item label="医院ID" prop="hospitalId">
        <el-input v-model.number="editForm.hospitalId" placeholder="请输入医院ID" type="number" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-switch v-model="editForm.status" active-text="启用" inactive-text="禁用" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCloseEditDialog">取消</el-button>
        <el-button type="primary" @click="handleSubmitEdit">确定</el-button>
      </span>
    </template>
  </el-dialog>

</template>


<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue';
import { ShowDepartments, AddDepartment, UpdateDepartment, DeleteDepartment } from '@/HTTPS/server';
import { reactive } from 'vue';
import moment from 'moment';
import { Grid, Plus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';

import type { UploadProps } from 'element-plus'


onMounted(()=>{
    show();
})

// 表格选择相关
const tableRef = ref();
const selectedRows = ref<any[]>([]);
// 处理选择变化
const handleSelectionChange = (selection: any[]) => {
    selectedRows.value = selection;
    console.log('当前选中的行:', selection);
}

const formInline = reactive({
    parentId:0,
  pageIndex: 1,
  pageSize:10
  
})



// 分页数据
const pagin = ref({
    totaleCount: 0,
    pageCount: 0,
})

// 监听分页参数变化
watch(formInline, () => {
    show();
}, { deep: true })

//显示
const tableData = ref([])
const show=()=>{
    ShowDepartments(formInline).then(res=>{
        console.log('API返回的数据:', res.data.data.list);
        tableData.value = res.data.data.list;
        pagin.value.pageCount = res.data.data.pageCount;
        pagin.value.totaleCount = res.data.data.totaleCount;
        // 清空选中状态
        selectedRows.value = [];
    })
}

// 查看下级科室
const viewSubDepartments = (row: any) => {
    console.log('查看下级科室，当前行数据:', row);
    // 将当前行的id赋值给parentId
    formInline.parentId = row.id;
    // 重置分页到第一页
    formInline.pageIndex = 1;
    // 调用show方法刷新列表数据
    show();
}

// 返回上级科室列表
const goBack = () => {
    console.log('返回上级科室列表');
    // 将parentId重置为0，返回到最初的科室列表
    formInline.parentId = 0;
    // 重置分页到第一页
    formInline.pageIndex = 1;
    // 调用show方法刷新列表数据
    show();
}

// 新增科室对话框相关
const addDialogVisible = ref(false);
const addFormRef = ref();
const addForm = reactive({
    name: '',
    introduction: '',
    hospitalId: 1,
    parentId: 0,
    status: true
});

// 父级科室列表
const parentDepartmentList = ref<any[]>([]);

// 编辑科室对话框相关
const editDialogVisible = ref(false);
const editFormRef = ref();
const editForm = reactive({
    id: 0,
    name: '',
    introduction: '',
    hospitalId: 1,
    parentId: 0,
    status: true
});

// 表单验证规则
const addFormRules = {
    name: [
        { required: true, message: '请输入科室名称', trigger: 'blur' },
        { min: 2, max: 50, message: '科室名称长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    introduction: [
        { required: true, message: '请输入科室介绍', trigger: 'blur' },
        { min: 2, max: 200, message: '科室介绍长度在 2 到 200 个字符', trigger: 'blur' }
    ],
    hospitalId: [
        { required: true, message: '请输入医院ID', trigger: 'blur' },
        { type: 'number', message: '医院ID必须为数字', trigger: 'blur' }
    ]
};

// 编辑表单验证规则
const editFormRules = {
    name: [
        { required: true, message: '请输入科室名称', trigger: 'blur' },
        { min: 2, max: 50, message: '科室名称长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    introduction: [
        { required: true, message: '请输入科室介绍', trigger: 'blur' },
        { min: 2, max: 200, message: '科室介绍长度在 2 到 200 个字符', trigger: 'blur' }
    ],
    hospitalId: [
        { required: true, message: '请输入医院ID', trigger: 'blur' },
        { type: 'number', message: '医院ID必须为数字', trigger: 'blur' }
    ]
};

// 获取父级科室列表
const getParentDepartments = () => {
    // 获取所有顶级科室作为父级选项
    const params = {
        parentId: 0,
        pageIndex: 1,
        pageSize: 100 // 获取更多数据用于选择
    };
    ShowDepartments(params).then(res => {
        console.log('获取父级科室列表:', res.data.data.list);
        parentDepartmentList.value = res.data.data.list || [];
    }).catch(err => {
        console.error('获取父级科室列表失败:', err);
        parentDepartmentList.value = [];
    });
};

// 打开新增对话框
const openAddDialog = () => {
    // 获取父级科室列表
    getParentDepartments();
    // 设置当前的parentId
    addForm.parentId = formInline.parentId;
    addDialogVisible.value = true;
};

// 关闭对话框
const handleCloseDialog = () => {
    addDialogVisible.value = false;
    // 重置表单
    addFormRef.value?.resetFields();
    addForm.name = '';
    addForm.introduction = '';
    addForm.hospitalId = 1;
    addForm.parentId = 0;
    addForm.status = true;
};

// 提交新增
const handleSubmitAdd = () => {
    addFormRef.value?.validate((valid: boolean) => {
        if (valid) {
            console.log('提交新增科室数据:', addForm);
            AddDepartment(addForm).then(res => {
                console.log('新增科室成功:', res);
                ElMessage.success('新增科室成功');
                handleCloseDialog();
                // 刷新列表
                show();
            }).catch(err => {
                console.error('新增科室失败:', err);
                ElMessage.error('新增科室失败');
            });
        } else {
            ElMessage.warning('请填写完整信息');
        }
    });
};

// 打开编辑对话框
const openEditDialog = (row: any) => {
    console.log('编辑科室，当前行数据:', row);
    // 获取父级科室列表
    getParentDepartments();
    // 填充编辑表单数据
    editForm.id = row.id;
    editForm.name = row.name;
    editForm.introduction = row.introduction;
    editForm.hospitalId = row.hospitalId || 1;
    editForm.parentId = row.parentId || 0;
    editForm.status = row.status;
    editDialogVisible.value = true;
};

// 关闭编辑对话框
const handleCloseEditDialog = () => {
    editDialogVisible.value = false;
    // 重置表单
    editFormRef.value?.resetFields();
    editForm.id = 0;
    editForm.name = '';
    editForm.introduction = '';
    editForm.hospitalId = 1;
    editForm.parentId = 0;
    editForm.status = true;
};

// 提交编辑
const handleSubmitEdit = () => {
    editFormRef.value?.validate((valid: boolean) => {
        if (valid) {
            console.log('提交编辑科室数据:', editForm);
            UpdateDepartment(editForm).then(res => {
                console.log('编辑科室成功:', res);
                ElMessage.success('编辑科室成功');
                handleCloseEditDialog();
                // 刷新列表
                show();
            }).catch(err => {
                console.error('编辑科室失败:', err);
                ElMessage.error('编辑科室失败');
            });
        } else {
            ElMessage.warning('请填写完整信息');
        }
    });
};

// 删除科室
const handleDelete = (row: any) => {
    console.log('删除科室，当前行数据:', row);
    ElMessageBox.confirm(
        `确定要删除科室"${row.name}"吗？此操作不可恢复！`,
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        // 用户确认删除
        const deleteData = {
            id: row.id
        };
        console.log('提交删除科室数据:', deleteData);
        DeleteDepartment(deleteData).then(res => {
            console.log('删除科室成功:', res);
            ElMessage.success('删除科室成功');
            // 刷新列表
            show();
        }).catch(err => {
            console.error('删除科室失败:', err);
            ElMessage.error('删除科室失败');
        });
    }).catch(() => {
        // 用户取消删除
        console.log('用户取消删除操作');
    });
};

</script>